﻿using AppSocketModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Text;

namespace AppSocketService.System
{
    public class SystemService : ISystemService
    {
        public List<GpsEnumType> GetGpsEnumTypeList(string GpsEnumName)
        {
            Dictionary<string, Type> dict = GetAllEnum();

            Type itemType = null;

            if (dict.ContainsKey(GpsEnumName))
            {
                List<GpsEnumType> list = new List<GpsEnumType>();

                  itemType = dict[GpsEnumName];


                var fields = itemType.GetFields(BindingFlags.Static | BindingFlags.Public);

                foreach (var item in fields)
                {
                    GpsEnumType gpsEnumType = new GpsEnumType();
                    gpsEnumType.EnumTypeName = itemType.Name;
                    gpsEnumType.Key = (int) item.GetValue(null);
                    gpsEnumType.Value = item.Name;

                    gpsEnumType.Description = GetDescription(itemType, gpsEnumType.Key);

                    list.Add(gpsEnumType);

                }

                return list;
            }
            else
                throw new ArgumentException("没有该枚举类型!");
             
        }

        private static Dictionary<string, Type> GetAllEnum()
        {
            Assembly ass = Assembly.Load("AppSocketModel");
            Type[] types = ass.GetTypes();
            Dictionary<string, Type> dict = new Dictionary<string, Type>();

            foreach (Type item in types)
            {
                if (item.IsEnum)
                {
                    dict.Add(item.Name, item);
                }
            }
            return dict;
        }

        private static string GetDescription(Type t, object value)
        {
            foreach (MemberInfo mInfo in t.GetMembers())
            {
                if (mInfo.Name == t.GetEnumName(value))
                {
                    foreach (Attribute attr in Attribute.GetCustomAttributes(mInfo))
                    {
                        if (attr.GetType() == typeof(DescriptionAttribute))
                        {
                            return ((DescriptionAttribute)attr).Description;
                        }
                    }
                }
            }
            return string.Empty;
        }
    }
}
